import type {MenuDataItem, Settings as LayoutSettings} from '@ant-design/pro-layout';
import {SettingDrawer} from '@ant-design/pro-layout';
import {PageLoading} from '@ant-design/pro-layout';
import {dynamic, RunTimeLayoutConfig} from 'umi';
import {history} from 'umi';
import RightContent from '@/components/RightContent';
import Footer from '@/components/Footer';
import defaultSettings from '../config/defaultSettings';
import React from "react";
import {fetchMenuData, getAllRoutes, getLoginUserInfo} from "@/services/configuration/config";
import LoadingComponent from '@ant-design/pro-layout/es/PageLoading';
import * as iconMap from '@ant-design/icons';
import {getRouteCache, setRouteCache} from "@/utils/localStoreUtil";

const loginPath = '/user/login';

const systemLogin = '/system/login'


/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading/>,
};


/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.LoginUserData;
  loading?: boolean;
  menuData?: MenuDataItem[] | undefined;
  fetchUserInfo?: () => Promise<API.LoginUserData | undefined>;
  getMenuList?: () => Promise<MenuDataItem[] | undefined>;
}> {
  const fetchUserInfo = async () => {
    try {
      const res : any = await getLoginUserInfo();
      return res.code === 10000 ? res.data : {};
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };

  const getMenuList = async () => {
    try {
      const res = await fetchMenuData();
      return res.code === 10000 ? res.data : [];
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };


  // 如果是登录页面，不执行
  if (history.location.pathname !== loginPath && history.location.pathname !== systemLogin) {
    const currentUser = await fetchUserInfo();
    const menuData = await getMenuList();

    return {
      menuData,
      getMenuList,
      fetchUserInfo,
      currentUser,
      settings: defaultSettings,
    };
  }
  return {
    menuData:[],
    getMenuList,
    fetchUserInfo,
    settings: defaultSettings,
  };
}

export function patchRoutes({routes}: any) {

  let routeCache:any[] = getRouteCache();
  if (routeCache && routeCache.length > 0 && routes[0]) {
    routeCache = dynamicComponent(routeCache);
    routes[0].routes.splice(-3, 0, ...routeCache);
  }
}

export async function render(oldRender: any) {

  const routeCache:[] = getRouteCache();

  if (!routeCache || routeCache.length == 0) {
    const res = await getAllRoutes();
    if (res.code === 10000) {
      setRouteCache(res.data);
      // normalizedRoutes = dynamicComponent(data);
    }
  }

  oldRender();
}


const dynamicComponent = (data: any[]) => {

  const arr: any[] = []

  for (let item of data) {
    if (item.component) {
      const name = item.component;
      item.component = dynamic({loader: () => import(`./pages/${name}/index.tsx`), loading: LoadingComponent})
    } else if (item.routes) {
      item.routes = dynamicComponent(item.routes);
    }

    arr.push(item);
  }

  return arr;
}

const loopMenuItem = (menus: MenuDataItem[]): MenuDataItem[] => (
  menus.map(({icon, routes, ...item}) => {
    return {
      ...item,
      icon: icon && React.createElement(iconMap[icon as string]),
      routes: routes && loopMenuItem(routes),
    }
  })
);


// ProLayout api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({initialState, setInitialState}) => {

  return {
    rightContentRender: () => <RightContent/>,
    disableContentMargin: false,
    footerRender: () => <Footer/>,
    // menu render load icon
    menuDataRender: (menuData) => loopMenuItem(menuData),
    menu: {
      params: initialState,
      request: async (params, defaultMenuData) => {
        return initialState?.menuData || [];
      },
    },
    menuHeaderRender: undefined,
    // add loading
    childrenRender: (children, props) => {
      if (initialState?.loading) return <PageLoading/>;
      return (
        <>
          {children}
          {!props.location?.pathname?.includes('/login') && (
            <SettingDrawer
              enableDarkTheme
              settings={initialState?.settings}
              onSettingChange={(settings) => {
                setInitialState((preInitialState) => ({
                  ...preInitialState,
                  settings,
                }));
              }}
            />
          )}
        </>
      );
    },
    ...initialState?.settings,
  };
};
